﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Galaktika.BI.Charting;
using Galaktika.BI.Extensibility;
using Galaktika.BI.Runtime.Services;

namespace Galaktika.BI.Silverlight.Controls
{
    public partial class DatePicker : UserControl, IBindableObject, IEditableObject
    {
        public DatePicker()
        {
            InitializeComponent();
            this.DateControl.IsTodayHighlighted = true;
            this.DateControl.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(DateParameter_EditValueChanging);
        }

        #region Properties
        public DateTime? Value
        {
            get; set;
        }

        private string m_InitialDateScript = string.Empty;
        /// <summary>
        /// Имя Скрипта для получения даты
        /// </summary>
        [Browsable(false)]
        public string AInitialDateScript
        {
            get
            {
                return this.m_InitialDateScript;
            }
            set
            {
                this.m_InitialDateScript = value;
            }
        }

        private string m_VariableToSelectedDate = string.Empty;
        /// <summary>
        /// Глобальная переменная для выбранной даты
        /// </summary>
        [Browsable(false)]
        public String AVariableToSelectedDate
        {
            set
            {
                this.m_VariableToSelectedDate = value;
            }
            get
            {
                return this.m_VariableToSelectedDate;
            }
        }

        private string m_FormatString = "";
        /// <summary>
        /// Строка форматирования для выбранной даты
        /// </summary>
        [Browsable(false)]
        public string AFormatString
        {
            get
            {
                return this.m_FormatString;
            }
            set
            {
                this.m_FormatString = value;
            }
        }
        #endregion Properties

        #region Events
        /// <summary>
        /// Изменение текущей даты в контроле
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DateParameter_EditValueChanging(object sender, SelectionChangedEventArgs e)
        {
           DateTime selectedDate = System.DateTime.Now;

           if (e.AddedItems[0] is DateTime)
           {
               //Новая дата  
               selectedDate = (DateTime) e.AddedItems[0];
               this.Value = selectedDate;
               //Сохраняем в глобальную переменную выбранную дату
               if (!string.IsNullOrEmpty(AVariableToSelectedDate))
               {
                   IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
                   IUserTaskManager taskManager = (IUserTaskManager)this.Context.Services.GetService(typeof(IUserTaskManager));
                   if (context != null && taskManager != null && !string.IsNullOrEmpty(AVariableToSelectedDate))
                   {
                       taskManager.RunTaskAsync(String.Format(Localization.AppTask_ExecutingServiceCommand, "Modify variable"), state =>
                                                                                                                                   {
                                                                                                                                       context.ModifyVariable(this.Context, AVariableToSelectedDate, selectedDate.ToString(this.AFormatString));
                                                                                                                                   }
                           );

                   }
               }
           }
        }
        #endregion Events

        #region Private Methods
        private void InitializeControlState()
        {
            if (!string.IsNullOrEmpty(AInitialDateScript))
            {
                IScriptEngine script = (IScriptEngine) this.Context.Services.GetService(typeof (IScriptEngine));
                if (script != null)
                {
                    FuncInvokeCheckResult check = script.CheckFuncInvoke(this.AInitialDateScript);
                    if (check.IsSuccess)
                    {
                        this.DateControl.Text = script.InvokeFunction(this.Context, check);
                    }
                    else
                    {
                        throw new InformationalException(
                            string.Format(
                                Localization.Exc_DatePickerStartState,
                                this.AInitialDateScript));
                    }
                }
            }
        }
        #endregion Private Methods

        #region IBindableObject Members

        private IBindingContext m_Context;
        public IBindingContext Context
        {
            get
            {
                return m_Context;
            }
            set
            {
                m_Context = value;
            }
        }

        private Dictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new Dictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }

        #endregion

        #region IEditableObject Members

        public void BeginEdit()
        {
            
        }

        public void CancelEdit()
        {
            
        }

        public void EndEdit()
        {            
            InitializeControlState();
            this.Value = this.DateControl.SelectedDate;
        }

        #endregion
    }
}
